<?php
	
	namespace Aspic;
	
	/**
	* Functions around "user request" (language, localization, etc.)
	*/
	class Local {
		
		/**
		* Get a language in $availableLangs that match users pref
		* (HTTP_ACCEPT_LANGUAGE). If there is no match, the first language in
		* $availableLangs will be returned
		*/
		public static function getLngFromUserPrefs($availableLangs) {
			$userLngs = static::getUserLngsByWeight();
			
			// Choix de la meilleure langue disponible
			foreach($userLngs as $weight => $code) {
				$ind = array_search($code, $availableLangs);
				
				if ($ind != -1) {
					
					return $availableLangs[$ind];
				}
			}
			
			// Ah ben zut alors, pas de bol
			return null;
		}
		
		/**
		* Return the user languages based on $lngString or HTTP_ACCEPT_LANGUAGE by default
		* The list is sorted by language weight (priority)
		*/
		public static function getUserLngsByWeight($lngString = null) {
			if(!$lngString) {
				$lngString = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
			}
			
			// Parse du header HTTP Accept-Language
			$langs = array();
			// Cet en-tete HTTP est de la forme en-US,en;q=0.8,fr;q=0.6
			foreach (explode(',', $lngString) as $httplang) {
				$rawlang = explode(';q=', $httplang);
				
				if (strpos($rawlang[0], '-') !== FALSE) {
					// On ne garde que la partie "langue" de la locale, si jamais
					$rawlang[0] = substr($rawlang[0], 0, strpos($rawlang[0], '-'));
				}
				
				if (count($rawlang) == 1) {
					$rawlang[1] = 1.0; // Si aucun poids n'est precise, c'est que le poids vaut 1
				}
				
				$langs[$rawlang[1]] = $rawlang[0]; // Z'avez qu'a mettre des poids distincts :p
			}
			
			krsort($langs, SORT_NUMERIC);
			
			return $langs;
		}
		
	}	
	
?>